<template>
	<view class="container">
		<view class="image">
			<uv-image class="image-item" :src="imageUrl" width="416rpx" height="512rpx"></uv-image>

		</view>
		<view class="title">
			<text> {{audioInfo.bookName}} </text> <br>
			<view class="desc">
				{{audioInfo.author}}
			</view>
		</view>

		<view class="audio-player">
			<!-- <view style="margin-left: 40rpx;">{{audioInfo.}}</view> -->
			<uv-slider v-model="currentTime" :max="duration" :disabled="!isLoaded" @input="seekTo"></uv-slider>
			<view class="time-container">
				<span class="time">{{ formatTime(currentTime) }}</span>
				<span class="time total-time">{{ formatTime(duration) }}</span>
			</view>
			<view class="play_button">

				<image v-if="data.loopMode==0" class="loop" src="../../../static/列表循环.png"
					style="width: 48rpx; height: 49rpx;" @click="loopModeChange"></image>
				<image v-else class="loop" src="../../../static/单曲循环.png" style="width: 48rpx; height: 49rpx;"
					@click="loopModeChange"></image>

				<image class="last" :src="lasts" @click="playPreviousTrack" style="width: 64rpx; height: 64rpx;">
				</image>
				<image v-if="playto" @click="togglePlay" class="play" :src="plays"
					style="width: 120rpx; height: 120rpx;"></image>
				<image v-else @click="togglePlay" class="play" :src="stops" style="width: 120rpx; height: 120rpx;">
				</image>
				<image class="next" :src="nexts" @click="playNextTrack" style="width: 64rpx; height: 64rpx;"></image>
				<image class="play_list" @click="open" :src="lists" style="width: 48rpx; height: 48rpx;"></image>

			</view>
		</view>
		<view class="popup">
			<uv-popup ref="popup" :safeAreaInsetBottom="false" :safeAreaInsetTop="true" :customStyle="stylePopup"
				duration="500" mode="bottom" round="10">
				<view class="list_title">
					播放全部
					<uv-image src="../../../static/播放——音频详情.png" width="32rpx" height="32rpx"
						style="margin-left: 10rpx;"></uv-image>
				</view><br>
				<uv-divider class="divider2" />
				<view class="video_list">
					<view class="list" v-for="(item,index) in audioListTo" :key="index">
						<view @click="playSelectAudio(index,item.fileName)">
							<view class="list_titles">{{item.fileName}}</view>
							<!-- <view class="audio_icon">
								<view class="con-audio" v-if="list.openMusic" bindtap="conMusic">
									<section>
							
										<span
											style="animation-play-state:{{list.openMusic == true ? 'running' : 'paused'}}"></span>
										<span
											style="animation-play-state:{{list.openMusic == true ? 'running' : 'paused'}}"></span>
										<span
											style="animation-play-state:{{list.openMusic == true ? 'running' : 'paused'}}"></span>
										<span
											style="animation-play-state:{{list.openMusic == true ? 'running' : 'paused'}}"></span>
									</section>
								</view>
							</view> -->

							<view class="mb">
								<image class="file_icon" src="../../../static/文件大小.png"></image>
								<view class="mb_font">
									{{item.size}}MB
								</view>
								<image class="file_icon2" src="../../../static/播放——音频详情.png"></image>
							</view>
							<uv-divider class="divider2" />
						</view>

					</view>
				</view>
			</uv-popup>
		</view>
		<!-- 		<uv-button @click="onPlayHandler" text="asdasda"></uv-button> -->
		<!-- 		<view style="display: none;">
			<lm-audio ref="audioComponent" :src="audioSource" @onPlay="onPlayHandler" @click="Handler"
				@ed="edHandler"></lm-audio>

		</view> -->
		<!-- <lm-audio :src="audioSource" :innerStyle="{ /* your styles here */ }"
		      @onPlay="handlePlay" @onPause="handlePause" @onStop="handleStop" @onEnded="handleEnded"
		    /> -->
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted,
		onBeforeUnmount,
		reactive
	} from 'vue';
	import {
		onLoad
	} from '@dcloudio/uni-app'
	import useGetGlobalProperties from '@/util/useGlobal.js'
	const wxurl = useGetGlobalProperties().$httpUrlWx;
	const lists = wxurl + '/list.png'
	const plays = wxurl + '/play.png'
	const stops = wxurl + '/stop.png'
	const lasts = wxurl + '/last.png'
	const nexts = wxurl + '/next.png'
	let audioSource = ref('https://music.163.com/song/media/outer/url?id=95475.mp3');
	const list = reactive({
		list: [{
				titile: '最美小说文丛 文丛中国 01.mp3',
				mb: '35.37M',
				src: '../../../static//播放——音频详情.png'
			},
			{
				titile: '最美小说文丛 文丛中国 01.mp3',
				mb: '35.37M',
				src: '../../../static//播放——音频详情.png'
			},
			{
				titile: '最美小说文丛 文丛中国 01.mp3',
				mb: '35.37M',
				src: '../../../static//播放——音频详情.png'
			},
			{
				titile: '最美小说文丛 文丛中国 01.mp3',
				mb: '35.37M',
				src: '../../../static//播放——音频详情.png'
			},
			{
				titile: '最美小说文丛 文丛中国 01.mp3',
				mb: '35.37M',
				src: '../../../static//播放——音频详情.png'
			}

		],
		openMusic: true
	})
	const stylePopup = {
		height: '1000rpx',
		overflowY: 'scroll'
	}
	// const audioList = [
	//   'https://music.163.com/song/media/outer/url?id=95477.mp3', // 第一首音频的URL
	//   'https://music.163.com/song/media/outer/url?id=95475.mp3', // 第二首音频的URL
	//   'https://music.163.com/song/media/outer/url?id=95478.mp3', // 第三首音频的URL
	//   'https://music.163.com/#/song?id=1303027499.mp3'
	// ];
	const audioList = ref([]);
	let currentTrackIndex = 0; // 当前播放的音频索引
	// const audio = new Audio(audioList[currentTrackIndex]);
	const loopModeChange = () => {

		if (data.loopMode == 1) {
			data.loopMode = 0;
			uni.showToast({
				title: '列表循环模式',
				duration: 2000
			});
		} else {
			data.loopMode = 1;
			uni.showToast({
				title: '单曲循环模式',
				duration: 2000
			});
		}
		console.log(data.loopMode);
	}
	const data = reactive({
		loopMode: 0
	})



	let updateProgressInterval = ''
	//播放时的处理
	const onPlayHandler = (e) => {
		console.log('Audio is playing', e);
		// audioComponent.value.play();
		console.log(e)
		// 启动定时器，定时更新进度条的值
		updateProgressInterval = setInterval(() => {
			updateProgress();
		}, 1000);
	}
	const updateProgress = () => {
		// currentTime.value = audioComponent.value.nowTime;
		// // 确保 currentTime 是一个有效的数字
		// // if (!isNaN(currentTime.value)) {
		// //   currentTime.value = formatTime(currentTime.value);
		// // }
		// //duration.value = formatTime(audioComponent.value.audioContext.duration);
		// // 更新当前播放时间和进度条的值
		// //   currentTime.value = formatTime(currentTime);
		// //   duration.value = formatTime(duration);

		// // 如果音频播放完成，清除定时器
		// if (audioComponent.value.audioContext.paused || audioComponent.value.audioContext.ended) {
		// 	clearInterval(updateProgressInterval);
		// }
	};
	const edHandler = () => {

	}

	const changeTrack = () => {
		audio.src = audioList[currentTrackIndex];
		play();
	};
	const changeTrackIfAutoPlay = () => {
		if (data.loopMode === 0) {
			// 列表循环模式下自动播放下一首
			playNextTrack();
		} else if (data.loopMode === 1) {
			// 单曲循环模式下重新播放当前音频
			changeTrack();
		}
	};


	const popup = ref(null);
	const isPlaying = ref(false);
	const currentTime = ref(0);
	const duration = ref(null);
	const isLoaded = ref(false);
	const playto = ref(false);
	const togglePlay = () => {
		if (isPlaying.value) {
			pause();
		} else {
			play();
		}


	};
	const open = () => {
		popup.value.open();
	}
	let audioComponent = null;
	const play = () => {
		//audioComponent.src = audioList.value[audiIndex.value];
		audioComponent.play()
		isPlaying.value = true;
		playto.value = true;
		console.log('audioPlay', audioComponent)
		// duration.value = audioComponent.duration
		// console.log('src', audioList.value[audiIndex.value])
		// console.log('srcc', audioComponent.value.src)
		//console.log('audioPlayTime', audioComponent.value.duration)
		//duration.value = audioComponent.value.duration
		onMonitorEvents()
		console.log('duration', audioComponent.duration)
		audioComponent.onCanplay(() => {
			// 必须
			setTimeout(() => {
				duration.value = audioComponent.duration
			}, 1000)
			console.log('the audio is canPlay......')
			console.log('duration', audioComponent.duration)
		});
		audioComponent.onTimeUpdate(function(){
			setTimeout(() => {
				duration.value = audioComponent.duration
				console.log('onTimeUpdate!!!!!!!!!!!', audioComponent.duration)
				if (uni.getSystemInfoSync().platform === 'ios') {
						updatePlayTime();
				}
			}, 1000)
		})
		// 播放进度
		

	};
	let pauseTime = ref();
	const pause = () => {
		//audio.pause();
		//pauseTime.value = audioComponent.value.audioContext.currentTime
		console.log('audioPlay', audioComponent)
		audioComponent.pause()

		isPlaying.value = false;
		playto.value = false;
	};

	const updateTime = () => {

	};

	const seekTo = (value) => {
		console.log('seek', value);
		currentTime.value = value;
		audioComponent.value.seek(currentTime.value);
	};

	const formatTime = (time) => {
		if (!time || Number.isNaN(time)) return '00:00';

		const minutes = Math.floor(time / 60);
		const seconds = Math.floor(time % 60);

		const formattedMinutes = String(minutes).padStart(2, '0');
		const formattedSeconds = String(seconds).padStart(2, '0');

		return `${formattedMinutes}:${formattedSeconds}`;
	};
	// 使用 ref 获取 lmAudio 组件实例
	//const audioComponent = ref();
	const audioInfo = ref({
		bookName: '',
		author: ''
	});
	const imageUrl = ref('');
	const audioListTo = ref();
	const audiIndex = ref();
	const init = () => {
		audioComponent = uni.createInnerAudioContext();
		audioComponent.loop = true;
		audioComponent.obeyMuteSwitch = true; 
		// 为了防止苹果手机静音无法播放
		uni.setInnerAudioOption({
			obeyMuteSwitch: false
		});
		audioComponent.onPlay(function(res) {
			console.log('lm', res)
			duration.value = audioComponent.duration
		});
		audioComponent.onPause(function(res) {
			console.log('onPause', res)
		});
		audioComponent.onStop(function(res) {
			console.log('onStop', res)
		});
		audioComponent.onEnded(function(res) {
			console.log('onEnded', res)
		});
		audioComponent.onError(function(res) {
			console.log('onError', res)
		});

		console.log('audio', audioComponent)
		audioListTo.value = uni.getStorageSync('audio');
		audioInfo.value = uni.getStorageSync('audioInfo');
		imageUrl.value = audioInfo.value.coverPictures[0].coverPictureUrl
		console.log('t', audioListTo.value)
		for (let i = 0; i < audioListTo.value.length; i++) {
			audioList.value.push(audioListTo.value[i].fileUrl);
		}
		console.log('asdasd', audioList.value)
		audiIndex.value = uni.getStorageSync('audioIndex');
		audioComponent.src = audioList.value[audiIndex.value];
		// if(uni.getSystemInfoSync().platform === 'ios'){
		// 	audioComponent.src = encodeURI(audioList.value[audiIndex.value])+ '?'+Date.now()
		// 	console.log('ios',audioComponent.src)
		// }else{
		// 	audioComponent.src = encodeURI(audioList.value[audiIndex.value]);
		// 	console.log('anhord',audioComponent.src)
		// }
		
		// audioComponent.onCanplay(() => {
		// 	// 必须
		// 	setTimeout(() => {
		// 		duration.value = audioComponent.duration
		// 		console.log('setTimeout!!!!!!!!!!!', audioComponent)
		// 	}, 500)
		// 	console.log('the audio is canPlay......')
		// });
		audioComponent.onTimeUpdate(function(){
			 updateTimer = setTimeout(() => {
				duration.value = audioComponent.duration
				console.log('onTimeUpdate!!!!!!!!!!!', audioComponent.duration)
			}, 5000)
		})
		// 播放进度
		if (uni.getSystemInfoSync().platform === 'ios') {
			audioComponent.onTimeUpdate(() => {
				duration.value = audioComponent.duration
				console.log('init',audioComponent.duration)
			});
		}
		
	}
	const playSelectAudio = (e, fileName) => {
		audiIndex.value = e;
		console.log('fileName', fileName)
		audioInfo.value.bookName = fileName;
		console.log('audiIndex.value', audiIndex.value)
		Pushea();
		clearInterval(updateTimer);
		//切换播放资源
		audioComponent.src = audioList.value[e];

		onMonitorEvents();
		//隐藏抽屉图层
		popup.value.close();
		setTimeout(() => {
			duration.value = audioComponent.duration
			console.log('setTimeout', audioComponent)
		}, 1000)
		//图标变成暂停
		isPlaying.value = false;
		playto.value = false;

		currentTime.value = '0'
		console.log('audioSource', audioSource.value)
	}
	const playNextTrack = () => {
		

		if (audiIndex.value == audioList.value.length) {
			uni.showToast({
				title: '这是最后一首',
				icon: 'error'
			})
			return;
		}
		audiIndex.value++
		Pushea(audioList.value[audiIndex.value]);
		audioInfo.value.bookName = audioListTo.value[audiIndex.value].fileName;
		audioComponent.src = audioList.value[audiIndex.value];
		//图标变成暂停
		isPlaying.value = false;
		playto.value = false;
		setTimeout(() => {
			duration.value = audioComponent.duration
			console.log('setTimeout', audioComponent.duration)

		}, 1000)
		audioComponent.onCanplay(() => {
			// 必须
			setTimeout(() => {
				duration.value = audioComponent.duration
			}, 1000)
			console.log('the audio is canPlay......')
			console.log('duration', audioComponent.duration)
		});
		// 播放进度
		// if (uni.getSystemInfoSync().platform === 'ios') {
		// 	this.innerAudioContext.onTimeUpdate(() => {
		// 		duration.value = audioComponent.duration
		// 		currentTime.value = audioComponent.duration
		// 	});
		// }
		uni.showToast({
			title: '切换成功,请点击播放继续',
			icon: 'success'
		})
	}
	const Pushea = (e) => {
		if (audioComponent) {
			currentTime.value = 0;
			destroy()
			audioComponent = null;
		}
		audioComponent = uni.createInnerAudioContext();
		audioComponent.loop = true;
		audioComponent.obeyMuteSwitch = true;
		// 为了防止苹果手机静音无法播放
		uni.setInnerAudioOption({
			obeyMuteSwitch: false
		});
		audioComponent.onPlay(function(res) {
			console.log('lm', res)
			duration.value = audioComponent.duration
		});
		audioComponent.onPause(function(res) {
			console.log('onPause', res)
		});
		audioComponent.onStop(function(res) {
			console.log('onStop', res)
		});
		audioComponent.onEnded(function(res) {
			console.log('onEnded', res)
		});
		audioComponent.onError(function(res) {
			console.log('onError', res)
		});
		audioComponent.src = encodeURI(e);
		console.log('pusha',audioComponent);
		// 播放进度
		if (uni.getSystemInfoSync().platform === 'ios') {
			audioComponent.onTimeUpdate(() => {
				duration.value = audioComponent.duration
				console.log('init',audioComponent.duration)
			});
		}
		audioComponent.onTimeUpdate(function(){
			 updateTimer = setTimeout(() => {
				duration.value = audioComponent.duration
				console.log('onTimeUpdate!!!!!!!!!!!', audioComponent.duration)
			}, 5000)
		})
	}
	const playPreviousTrack = () => {
		
		if (audiIndex < 0) {
			uni.showToast({
				title: '这是第一首',
				icon: 'error'
			})
			return;
		}
		audiIndex.value--
		Pushea(audioList.value[audiIndex.value]);
		audioComponent.src = audioList.value[audiIndex.value];
		audioInfo.value.bookName = audioListTo.value[audiIndex.value].fileName;
		//图标变成暂停
		isPlaying.value = false;
		playto.value = false;
		uni.showToast({
			title: '切换成功,请点击播放继续',
			icon: 'success'
		})
	};
	let updateTimer = null;
	// 监听
	const onMonitorEvents = () => {
		updateTimer = setInterval(() => {
			updatePlayTime();
		}, 500)
	}
	const updatePlayTime = () => {
		currentTime.value = audioComponent.currentTime;
		duration.value = audioComponent.duration;
		if (currentTime == '') {
			clearInterval(updateTimer);
		}
	}
	const destroy = ()=>{
		if(audioComponent){
			clearInterval(updateTimer);
		}
		audioComponent.destroy();

	}
	onLoad((option) => {

	});
	onMounted(() => {
		init()
	});
	onBeforeUnmount(() => {
		destroy();
	});
</script>

<style>
	.audio_icon {}

	.con-audio {
		animation: backColor 4s infinite;
		z-index: 2;
		position: fixed;
		left: 50rpx;
		width: 50rpx;
		height: 50rpx;

	}

	.con-audio section {
		position: absolute;
		left: 530rpx;
		bottom: 40rpx;
		width: 100%;
		height: 100%;

	}



	.con-audio span {
		width: 2px;
		height: 30rpx;
		border-radius: 10rpx 10rpx 0rpx 0rpx;
		border: 1px dashed #8a8a8a;
		bottom: 0rpx;
		position: absolute;
		background: #008bff;
		color: #008bff;
	}

	.con-audio span:nth-child(1) {
		width: 2px;
		animation: loading 0.4s 0.3s linear infinite alternate;
		animation-play-state: running;
	}

	.con-audio span:nth-child(2) {
		left: 13rpx;
		animation: loading 0.5s 0.5s linear infinite alternate;
		animation-play-state: running;
	}

	.con-audio span:nth-child(3) {
		left: 25rpx;
		animation: loading 0.6s 0.8s linear infinite alternate;
		animation-play-state: running;
	}

	.con-audio span:nth-child(4) {
		left: 37rpx;
		animation: loading 0.4s 0.3s linear infinite alternate;
		animation-play-state: running;
	}


	@keyframes loading {
		0% {
			height: 30rpx;
		}

		100% {
			height: 5px;
		}
	}

	@keyframes loading {
		0% {
			height: 30rpx;
			/* transform: translateY(0); */
		}

		100% {
			height: 5px;
			/* transform: translateY(7.5px); */
		}
	}



	.divider2 {
		margin-top: 10rpx;
	}

	.list_titles {
		font-size: 30rpx;
		margin-left: 50rpx;
	}

	.mb {
		display: flex;
		color: #86909C;
		margin-top: 5rpx;
		margin-left: 50rpx;
	}

	.mb_font {
		font-family: Source Han Sans CN-Regular;
		margin-left: 8rpx;
		font-size: 24rpx;
		margin-top: 8rpx;
	}

	.file_icon2 {
		width: 38rpx;
		height: 38rpx;
		margin-left: auto;
		margin-right: 50rpx;
		margin-top: -16px;
	}

	.file_icon {
		width: 30rpx;
		height: 28rpx;
		margin-top: 10rpx;

	}

	.list_title {
		display: flex;
		align-items: center;
		margin-left: 48rpx;
		position: relative;
		top: 30rpx;

		font-size: 32rpx;
	}

	.play_list {
		margin-left: 80rpx;
	}

	.next {
		margin-left: 70rpx;

	}

	.play {
		margin-left: 64rpx;
	}

	.last {
		margin-left: 80rpx;
	}

	.play_button {
		display: flex;
		align-items: center;
		margin-top: 80rpx;
	}

	.loop {
		margin-left: 35rpx;

	}

	.time-container {
		display: flex;
		justify-content: space-between;
	}


	.time {
		font-size: 13px;
		color: #86909C;
		margin-left: 40rpx;

	}


	.total-time {
		text-align: right;
		color: #86909C;
		margin-right: 40rpx;
	}


	.audio-player {
		position: relative;
		bottom: 10rpx;
		font-family: my-font;
		height: 200px;
	}


	.progress {
		width: 100%;
	}


	.container {
		padding: 0 20rpx;
		font-family: my-font;
	}

	.image {
		display: flex;
		align-items: center;
		justify-content: center;
		text-align: center;

		padding-top: 320rpx;

		/* 设置高度为屏幕高度的一半 */
	}

	.image-item {
		box-shadow: 0rpx 0rpx 90rpx 0rpx rgba(0, 0, 0, 0.3);
		overflow: hidden;
		/* 剪裁溢出的圆角部分 */
		border-radius: 20rpx;
		margin-bottom: 100rpx;
		/* 设置圆角 */
	}

	.title {
		font-family: my-font;
		font-size: 36rpx;
		margin: 10%;
		display: grid;
		place-items: center;
	}

	.desc {
		font-size: 24rpx;
		color: #7a7e86;
		margin-top: 7rpx;
		font-family: Source Han Sans CN-Regular, Source Han Sans CN;
		text-align: center;
		grid-row: 2;
	}
</style>